package com.ecfront.service.impl;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.ecfront.exception.WebSiteException;
import com.ecfront.service.EmailSender;
import com.ecfront.service.WebSiteService;
import com.ecfront.util.email.MailContext;
/**
 * 邮件发送封装类
 * @author www.ecfront.com
 */
public class EmailSenderImpl implements EmailSender {

	private static WebSiteService webSiteService;
	
    private JavaMailSenderImpl mailSender;
	private MimeMessage message;
	private MimeMessageHelper helper;
    
	private static String username;//邮件发送用户名
	private static String password;//邮件发送密码
	private static String host;//邮件发送服务器
		
	public void setMailSender(JavaMailSenderImpl mailSender) {
		this.mailSender = mailSender;
	}
	public void setWebSiteService(WebSiteService webSiteService) {
		this.webSiteService = webSiteService;
	}
	/**
	 * 初始化Email发送的各项参数
	 * @throws WebSiteException
	 */
	private void init() throws WebSiteException{
		username = webSiteService.getSmtpName();
		password = webSiteService.getSmtpPass();			
		host = webSiteService.getSmtpSerice();
			
		mailSender.setHost(host);
		mailSender.setUsername(username);
		mailSender.setPassword(password);
		
		message = mailSender.createMimeMessage();
		try {
			helper = new MimeMessageHelper(message,true,"gbk");//创建message的辅助类
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * 发送邮件
	 * @param toEmail 发送到的用户
	 * @param subject 发送到标题
	 * @param body 发送到正文
	 */
	public void sendMessage(String toEmail, String subject, String body) {
		SimpleMailMessage msg = null;
		try{
			init();
			helper.setFrom(username);
			helper.setTo(toEmail);
			helper.setText(body,true);
			helper.setSubject(subject);
			
			mailSender.send(message);
			
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 发送邮件
	 * @param mailContext 发送内容封装包
	 */
	public void sandMessage(MailContext mailContext) {
		sendMessage(mailContext.getToEmail(),
					mailContext.getSubject(),
					mailContext.getEmailBody());
	}
}
